import { Prefab } from 'cc';
import { Vec3 } from 'cc';
import { find } from 'cc';
import { instantiate } from 'cc';
import { ProgressBar } from 'cc';
import { _decorator, Component, Node } from 'cc';
import { gameComponent } from '../gameComponent';
const { ccclass, property } = _decorator;

@ccclass('treeComponent')
export class treeComponent extends Component {

    @property({type : Number}) //血量 如果血量为-1 则视为无限血量
    blood = 350;

    @property(Prefab)
    wood_prefab : Prefab = null; // 木头
    
    curBlood = this.blood;

    start() {

    }

    //生成掉落的资源
    createWood(){
        console.log("==========掉落树木==========")
        let random = Math.random() > 0.5 ? 2 : 3;
        for(let i = 0 ; i < random ; i++){
            let wood = instantiate(this.wood_prefab);
            let treePos = this.node.position;
            let dirX = Math.random() > 0.5 ? 1 : -1;
            let dirY = Math.random() > 0.5 ? 1 : -1;
            wood.setPosition(new Vec3(treePos.x + dirX * Math.random() * 20,treePos.y + dirY * Math.random() * 20,0));
            wood.parent = this.node.parent;
            find("Canvas").getComponent(gameComponent).addContent(wood);
        }
    }

    //更新敌人的血量
    updateTreeBlood(value){
        if(this.curBlood <= 0) return;
        this.curBlood -= value;
        let blood_progress = this.node.getChildByName("blood");
        blood_progress.getComponent(ProgressBar).progress = this.curBlood / this.blood;
        if(this.curBlood <= 0){
            this.node["unCheck"] = true;
            console.log("==========树消除=========");
            let self = this;
            setTimeout(()=>{
                this.createWood();
                self.node.destroy();
            },100)
        }
    }
}


